/**
 * 代码文件压缩混淆
 *
 * 需要安装以下依赖:
 * npm install terser
 */

const fs = require('fs');
const path = require('path');
const { minify } = require('terser');
const toolsNode = require('../libs/tools-node');

// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let toDirRoot = path.dirname(from);
let toName = path.basename(from);
toName = toName.replace(/^format_/i, '');
let to = path.join(toDirRoot, `compress_${toName}`);

// 配置 Terser 选项
const terserOptions = {
  compress: {
    drop_console: true, // 移除 console 语句
    dead_code: true, // 移除不可达代码
    warnings: false // 不显示警告
  },
  mangle: true, // 混淆变量名
  format: {
    comments: false // 移除注释
  },
};

async function compressFile(inputPath, outputPath, options = {}) {
  try {
    let fileContent = fs.readFileSync(inputPath, 'utf8');
    // 使用 Terser 压缩代码
    let result = await minify({ [path.basename(inputPath)]: fileContent }, options);
    // 检查是否有错误
    if (result.error) {
      console.error('压缩过程中发生错误:', result.error);
      return;
    }
    // 写入压缩后的代码到输出文件
    toolsNode.writeFileSync(outputPath, result.code, 'utf8');
    console.log(`成功压缩文件: ${inputPath} → ${outputPath}`);
    // 如果生成了源映射
    if (result.map) {
      const mapPath = outputPath + '.map';
      toolsNode.writeFileSync(mapPath, result.map, 'utf8');
      console.log(`生成的源映射文件: ${mapPath}`);
    }
  } catch (error) {
    console.error('压缩过程中出错:', error);
    process.exit(1);
  }
}

compressFile(from, to, terserOptions);
